﻿using EnvDTE;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Axiom.CodeManifold
{
	public static class ProjectExtensions
	{
		public static IList<FileCodeModel> GetCodeModels(this Project project)
		{
			var result = new List<FileCodeModel>();

			var items = project.GetProjectItems();
			foreach (ProjectItem item in items)
			{
				FileCodeModel model = item.FileCodeModel;
				if (model != null)
				{
					result.Add(model);
				}
			}

			return result;
		}

		public static IList<ProjectItem> GetProjectItems(this Project project)
		{
			if (project == null)
			{
				throw new ArgumentNullException("Project cannot be null");
			}

			var results = new List<ProjectItem>();
			foreach (ProjectItem item in project.ProjectItems)
			{
				results.Add(item);

				if (item.ProjectItems == null)
				{
					continue;
				}

				GetProjectItemsRecoursive(item, results);
			}

			return results;
		}

		private static void GetProjectItemsRecoursive(ProjectItem item, IList<ProjectItem> collection)
		{
			foreach (ProjectItem projectitem in item.ProjectItems)
			{
				collection.Add(projectitem);
				GetProjectItemsRecoursive(projectitem, collection);
			}
		}

		public static IDictionary<string,string> GetProperties(this Project project)
		{
			var results = new Dictionary<string, string>();
			var temp = new Dictionary<string, string>();

			for (int i = 0; i < project.Properties.Count; i++)
			{
				try
				{
					var value = project.Properties.Item(i);
					if (value.Value != null && !string.IsNullOrWhiteSpace(value.Value.ToString()))
					{
						temp.Add(value.Name, value.Value);
					}
				}
				catch (Exception ex)
				{

				}
			}
			var list = temp.ToList();
			list.Sort((a, b) => a.Key.CompareTo(b.Key));
			foreach (var pair in list)
			{
				results.Add(pair.Key,pair.Value);
			}

			return results;
		}
	}
}
